document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const nameInput = document.getElementById('name');
    const ageInput = document.getElementById('age');
    const idCardInput = document.getElementById('id-card');
    const phoneInput = document.getElementById('phone');
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirm-password');
    const emailInput = document.getElementById('email');
    const addressInput = document.getElementById('address');
    const companyNameInput = document.getElementById('company-name');
    const companyAddressInput = document.getElementById('company-address');
    const companyPhoneInput = document.getElementById('company-phone');
    const companyCreditCodeInput = document.getElementById('company-credit-code');
    const registerBtn = document.getElementById('register-btn');
    const returnBtn = document.getElementById('return-btn');
    const alertBox = document.getElementById('alert-box');
    
    // 注册按钮点击事件
    registerBtn.addEventListener('click', function() {
        const name = nameInput.value.trim();
        const gender = document.querySelector('input[name="gender"]:checked').value;
        const age = ageInput.value.trim();
        const idCard = idCardInput.value.trim();
        const phone = phoneInput.value.trim();
        const password = passwordInput.value.trim();
        const confirmPassword = confirmPasswordInput.value.trim();
        const email = emailInput.value.trim();
        const address = addressInput.value.trim();
        const companyName = companyNameInput.value.trim();
        const companyAddress = companyAddressInput.value.trim();
        const companyPhone = companyPhoneInput.value.trim();
        const companyCreditCode = companyCreditCodeInput.value.trim();
        
        // 表单验证 - 个人信息
        if (!name) {
            showAlert('请输入真实姓名');
            return;
        }
        
        if (!age) {
            showAlert('请输入年龄');
            return;
        }
        
        if (isNaN(age) || parseInt(age) <= 0) {
            showAlert('请输入有效的年龄');
            return;
        }
        
        if (!idCard) {
            showAlert('请输入身份证号码');
            return;
        }
        
        // 确保身份证号码是18位
        if (idCard.length !== 18) {
            showAlert('身份证号码必须是18位');
            return;
        }
        
        if (!validateIdCard(idCard)) {
            showAlert('请输入有效的身份证号码，校验码错误');
            return;
        }
        
        if (!phone) {
            showAlert('请输入手机号');
            return;
        }
        
        if (!validatePhone(phone)) {
            showAlert('请输入有效的11位手机号');
            return;
        }
        
        if (!password) {
            showAlert('请输入密码');
            return;
        }
        
        if (password.length < 6) {
            showAlert('密码长度不能少于6位');
            return;
        }
        
        if (password !== confirmPassword) {
            showAlert('两次输入的密码不一致');
            return;
        }
        
        if (!email) {
            showAlert('请输入邮箱');
            return;
        }
        
        if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)) {
            showAlert('请输入有效的邮箱');
            return;
        }
        
        if (!address) {
            showAlert('请输入住址');
            return;
        }
        
        // 表单验证 - 公司信息
        if (!companyName) {
            showAlert('请输入公司名称');
            return;
        }
        
        if (!companyAddress) {
            showAlert('请输入公司地址');
            return;
        }
        
        if (!companyPhone) {
            showAlert('请输入公司电话');
            return;
        }
        
        if (!companyCreditCode) {
            showAlert('请输入统一社会信用代码');
            return;
        }
        
        // 发送注册请求
        fetch('register/manager', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `name=${encodeURIComponent(name)}&gender=${encodeURIComponent(gender)}&age=${age}&idCard=${encodeURIComponent(idCard)}&phone=${phone}&password=${encodeURIComponent(password)}&email=${encodeURIComponent(email)}&address=${encodeURIComponent(address)}&companyName=${encodeURIComponent(companyName)}&companyAddress=${encodeURIComponent(companyAddress)}&companyPhone=${encodeURIComponent(companyPhone)}&companyCreditCode=${encodeURIComponent(companyCreditCode)}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 注册成功，显示成功信息
                alertBox.textContent = data.message;
                alertBox.classList.remove('alert-danger');
                alertBox.classList.add('alert-success');
                alertBox.style.display = 'block';
                
                // 清空表单
                nameInput.value = '';
                ageInput.value = '';
                idCardInput.value = '';
                phoneInput.value = '';
                passwordInput.value = '';
                confirmPasswordInput.value = '';
                emailInput.value = '';
                addressInput.value = '';
                companyNameInput.value = '';
                companyAddressInput.value = '';
                companyPhoneInput.value = '';
                companyCreditCodeInput.value = '';
                
                // 3秒后跳转到登录页面
                setTimeout(function() {
                    window.location.href = 'index.html';
                }, 3000);
            } else {
                // 注册失败，显示错误信息
                showAlert(data.message);
            }
        })
        .catch(error => {
            console.error('注册请求失败:', error);
            showAlert('服务器错误，请稍后再试');
        });
    });
    
    // 返回按钮点击事件
    returnBtn.addEventListener('click', function() {
        window.location.href = 'index.html';
    });
    
    // 显示警告信息
    function showAlert(message) {
        alertBox.textContent = message;
        alertBox.classList.remove('alert-success');
        alertBox.classList.add('alert-danger');
        alertBox.style.display = 'block';
        
        // 3秒后自动隐藏
        setTimeout(function() {
            alertBox.style.display = 'none';
        }, 3000);
    }
    
    // 验证身份证号码
    function validateIdCard(idCard) {
        // 身份证号码为18位，前17位为数字，最后一位可能是数字或字母X
        const reg = /^\d{17}[\dXx]$/;
        if (!reg.test(idCard)) {
            return false;
        }
        
        // 验证前两位的省份编码是否有效（范围是11-65）
        const provinceCode = parseInt(idCard.substring(0, 2));
        if (provinceCode < 11 || provinceCode > 65) {
            return false;
        }
        
        // 验证出生日期是否有效
        const year = parseInt(idCard.substring(6, 10));
        const month = parseInt(idCard.substring(10, 12));
        const day = parseInt(idCard.substring(12, 14));
        
        const date = new Date(year, month - 1, day);
        // 检查日期是否有效
        if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
            return false;
        }
        
        // 验证身份证号码的校验码
        const coefficients = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        const lastCharacters = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        
        let sum = 0;
        for (let i = 0; i < 17; i++) {
            sum += parseInt(idCard.charAt(i)) * coefficients[i];
        }
        
        const remainder = sum % 11;
        const checkCode = lastCharacters[remainder];
        const lastChar = idCard.charAt(17).toUpperCase();
        
        return checkCode === lastChar;
    }
    
    // 验证手机号码
    function validatePhone(phone) {
        // 手机号码为11位数字，且以1开头
        return /^1[3-9]\d{9}$/.test(phone);
    }
    
    // 添加输入限制，只允许输入数字和X
    idCardInput.addEventListener('input', function() {
        this.value = this.value.replace(/[^\dXx]/g, '');
    });
    
    // 添加输入限制，只允许输入数字
    phoneInput.addEventListener('input', function() {
        this.value = this.value.replace(/\D/g, '');
    });
    
    // 添加公司电话输入限制，只允许输入数字和-
    companyPhoneInput.addEventListener('input', function() {
        this.value = this.value.replace(/[^\d-]/g, '');
    });
}); 